/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * DepRmPanel.java
 *
 * Created on 29/11/2011, 21:12:22
 */

package proj5labbd.graphics.dependente;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
import proj5labbd.DBInterface;
import proj5labbd.graphics.abstractOpGraphics.OperationPanel;

/*
 * Paine das operações DML de remoção de dependentes
 */
public class DepRmPanel extends OperationPanel {

    /** Creates new form DepRmPanel */
    public DepRmPanel(DepFrame frame, DBInterface dbInterface) {
        super(frame, dbInterface);
        initComponents();
        jbtRemove.addActionListener(new DepAction());
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jpParametros = new javax.swing.JPanel();
        jlbFuncionario = new javax.swing.JLabel();
        jtxtNome = new javax.swing.JTextField();
        jlbNomeDep = new javax.swing.JLabel();
        jtxtNomeDep = new javax.swing.JTextField();
        jlbDataNasc = new javax.swing.JLabel();
        jlbSexo = new javax.swing.JLabel();
        jcbSexo = new javax.swing.JComboBox();
        jftxtDate = new javax.swing.JFormattedTextField();
        jScrollPane1 = new javax.swing.JScrollPane();
        jtbRemove = new javax.swing.JTable();
        jbtRemove = new javax.swing.JButton();

        setBorder(javax.swing.BorderFactory.createTitledBorder("Remoção"));
        addComponentListener(new java.awt.event.ComponentAdapter() {
            public void componentShown(java.awt.event.ComponentEvent evt) {
                formComponentShown(evt);
            }
        });

        jpParametros.setBorder(javax.swing.BorderFactory.createTitledBorder("Parâmetros da remoção"));

        jlbFuncionario.setText("Nome do Funcionário");

        jlbNomeDep.setText("Nome do Dependente");

        jlbDataNasc.setText("Data de Nascimento");

        jlbSexo.setText("Sexo");

        jcbSexo.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "", "F", "M" }));

        try {
            jftxtDate.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.MaskFormatter("##-##-####")));
        } catch (java.text.ParseException ex) {
            ex.printStackTrace();
        }
        jftxtDate.setFocusLostBehavior(javax.swing.JFormattedTextField.COMMIT);

        javax.swing.GroupLayout jpParametrosLayout = new javax.swing.GroupLayout(jpParametros);
        jpParametros.setLayout(jpParametrosLayout);
        jpParametrosLayout.setHorizontalGroup(
            jpParametrosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jpParametrosLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jpParametrosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jlbFuncionario)
                    .addComponent(jtxtNome, javax.swing.GroupLayout.PREFERRED_SIZE, 248, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(jpParametrosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                        .addComponent(jftxtDate)
                        .addComponent(jlbDataNasc, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jpParametrosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jlbNomeDep)
                    .addComponent(jcbSexo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jlbSexo)
                    .addComponent(jtxtNomeDep, javax.swing.GroupLayout.PREFERRED_SIZE, 250, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(31, Short.MAX_VALUE))
        );
        jpParametrosLayout.setVerticalGroup(
            jpParametrosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jpParametrosLayout.createSequentialGroup()
                .addGroup(jpParametrosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jlbFuncionario)
                    .addComponent(jlbNomeDep))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jpParametrosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jtxtNome, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jtxtNomeDep, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jpParametrosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jpParametrosLayout.createSequentialGroup()
                        .addComponent(jlbDataNasc)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jftxtDate, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(jpParametrosLayout.createSequentialGroup()
                        .addComponent(jlbSexo)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jcbSexo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        jtbRemove.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {

            }
        ));
        jtbRemove.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jtbRemoveMouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(jtbRemove);

        jbtRemove.setText("Remover");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jbtRemove, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 90, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 565, Short.MAX_VALUE)
                            .addComponent(jpParametros, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                        .addContainerGap())))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jpParametros, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 258, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 9, Short.MAX_VALUE)
                .addComponent(jbtRemove))
        );
    }// </editor-fold>//GEN-END:initComponents

    //atuação após apresentação ao usuário
    private void formComponentShown(java.awt.event.ComponentEvent evt) {//GEN-FIRST:event_formComponentShown
        try {
            // TODO add your handling code here:
            setupTable();
        } catch (SQLException ex) {
            JOptionPane.showMessageDialog(null, "Não foi possível resgatar as informações da tabela");
            frame.printException(ex);
        }
    }//GEN-LAST:event_formComponentShown

    //atua após o click do mouse sobre o painel
    private void jtbRemoveMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jtbRemoveMouseClicked
        // TODO add your handling code here:
        jtbRemove.clearSelection();
    }//GEN-LAST:event_jtbRemoveMouseClicked


    //configuração da(s) tabela(s) utilizando dados resgatados da base de dados
    public void setupTable() throws SQLException {

        String [] fields = {"dependente.idFu","funcionario.nomeCompletoFu","dependente.nomeCompletoDe",
            "dependente.dataNascimentoDe","dependente.sexoDe"
        };
        String [] titles = {"ID Funcionario","Funcionario","Dependente","Data de nascimento","Sexo"};
        String [] params = {"funcionario.idFu=dependente.idFu"};
        String [][] result = dbInterface.view(fields,params,new String[]{"dependente","funcionario"});

        DefaultTableModel model = new DefaultTableModel(result,titles);
        jtbRemove.setModel(model);

    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JButton jbtRemove;
    private javax.swing.JComboBox jcbSexo;
    private javax.swing.JFormattedTextField jftxtDate;
    private javax.swing.JLabel jlbDataNasc;
    private javax.swing.JLabel jlbFuncionario;
    private javax.swing.JLabel jlbNomeDep;
    private javax.swing.JLabel jlbSexo;
    private javax.swing.JPanel jpParametros;
    private javax.swing.JTable jtbRemove;
    private javax.swing.JTextField jtxtNome;
    private javax.swing.JTextField jtxtNomeDep;
    // End of variables declaration//GEN-END:variables

    //ouvinte de evento do bootão de remoção
    class DepAction implements ActionListener {

        public void actionPerformed(ActionEvent e) {
            ArrayList<String> param = new ArrayList<String>();

                if (jtxtNome.getText().trim().compareTo("") != 0) {
                    try {
                        String[][] s = dbInterface.view(new String[]{"idFu"}, 
                                new String[]{"UPPER(funcionario.nomeCompletoFu)=UPPER('" + jtxtNome.getText() + "')"},
                                new String[]{"funcionario"});
                        param.add("dependente.idFu="+s[0][0]);
                    } catch (SQLException ex) {
                        Logger.getLogger(DepRmPanel.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }
                if (jtxtNomeDep.getText().trim().compareTo("") != 0) {
                    param.add("dependente.nomeCompletoDe='"+jtxtNomeDep.getText()+"'");
                }
                if (jftxtDate.getText().compareTo("  -  -    ") != 0) {
                    param.add("dependente.dataNascimentoDe="+"TO_DATE('"+jftxtDate.getText()+"','DD-MM-YYYY')");
                }
                if (jcbSexo.getSelectedItem().toString().trim().compareTo("") != 0) {
                    param.add("UPPER(dependente.sexoDe)=UPPER('"+jcbSexo.getSelectedItem().toString()+"')");
                }

                if (param.size() > 0) {
                    try {
                        String[] paramArray = new String[param.size()];
                        param.toArray(paramArray);
                        dbInterface.remove(paramArray, new String[]{"dependente"});
                    } catch (SQLException ex) {
                        frame.printException(ex);
                        JOptionPane.showMessageDialog(null, "Erro ao remover as tuplas desejadas.");
                    }
                } else {

                    if (jtbRemove.getSelectedRowCount() > 1) {
                    JOptionPane.showMessageDialog(null, "Você deve selecionar apenas uma linha da tabela.");
                    }
                    else if (jtbRemove.getSelectedRowCount() == 1) {
                        try {
                            String[] params = new String[2];
                            params[0] = "idFu=" + jtbRemove.getValueAt(jtbRemove.getSelectedRow(), 0);
                            params[1] = "UPPER(nomeCompletoDe)=UPPER('" + jtbRemove.getValueAt(jtbRemove.getSelectedRow(), 2)+"')";
                            dbInterface.remove(params, new String[]{"dependente"});
                        } catch (SQLException ex) {
                            frame.printException(ex);
                            JOptionPane.showMessageDialog(null, "Erro ao tentar remover a tupla.");
                        }
                    }
                    else if (jtbRemove.getSelectedRowCount() == 0) {
                        JOptionPane.showMessageDialog(null, "Você deve escolhar uma tupla ou um parâmetro para a remoção.");
                    }
                }
            try {
                setupTable();
            } catch (SQLException ex) {
                frame.printException(ex);
            }

        }
    }

}
